package com.dweb.myjsdemo;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.FormBindingData;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.content.Intent;
import ohos.rpc.IRemoteObject;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import java.util.Timer;
import java.util.TimerTask;

public class ServiceAbility extends Ability {
  private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
  private long formId;
  private int picNum = 0;

  @Override
  public void onStart(Intent intent) {
    HiLog.error(LABEL_LOG, "ServiceAbility::onStart");
    super.onStart(intent);
  }

  @Override
  public void onBackground() {
    super.onBackground();
    HiLog.info(LABEL_LOG, "ServiceAbility::onBackground");
  }

  @Override
  public void onStop() {
    super.onStop();
    HiLog.info(LABEL_LOG, "ServiceAbility::onStop");
  }

  @Override
  public void onCommand(Intent intent, boolean restart, int startId) {
    System.out.println("-----------尝试读取数据库onCommand----------");
    formId = intent.getLongParam("formId",0);
    System.out.println(formId);
    startTimer();
  }
  // 卡片更新定时器，每秒更新一次
  private void startTimer() {
    Timer timer = new Timer();
    long formId_value = formId;
    timer.schedule(
            new TimerTask() {
              @Override
              public void run() {
                updateForms(formId_value);
              }
            },
            0,
            1000L);
  }
  private void updateForms(long formId_value) {
    System.out.println("-----------刷新卡片----------");
    if (picNum==1){
      picNum = 2;
    }else{
      picNum = 1;
    }
    ZSONObject params = ZSONObject.stringToZSON("{\"itemContent\":\"定时换图启动中ing\",\"imageIndex\":\"\\/common\\/test"+picNum+".jpg\"}");
    FormBindingData bindingData = new FormBindingData(params);
    // 从数据库中获取卡片信息
//    updateForm(formId_value,bindingData);
    try {
      updateForm(formId,bindingData);
    } catch (FormException e) {
      e.printStackTrace();
    }
  }

  @Override
  public IRemoteObject onConnect(Intent intent) {
    return null;
  }

  @Override
  public void onDisconnect(Intent intent) {
  }
}